package logic

import (
	"fmt"
	"web-app/dao/mysql"
	"web-app/models"
	"web-app/pkg/jwt"
	"web-app/pkg/snowflake"
)

func SignUp(p *models.ParamSignUP) (err error) {
	//判断用户是否存在
	err = mysql.CheckUserExist(p.Username)
	if err != nil {
		return err
	}
	//生成UID
	userID := snowflake.GenID()
	fmt.Println("userID:   ", userID)
	//构造一个User实例
	u := models.User{
		UserID:   userID,
		Username: p.Username,
		Password: p.Password,
	}
	//保存进数据库

	return mysql.InsertUser(&u)
}

func Login(p *models.ParamLogin) (token string, err error) {
	user := models.User{
		Username: p.Username,
		Password: p.Password,
	}

	err = mysql.Login(&user)
	if err != nil {
		return "", err
	}
	//生成jwt的token
	return jwt.GenToken(user.UserID, user.Username)

}
